package com.kgdev.cweb.mbean.global.session;

import java.io.Serializable;
import java.security.Principal;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.kgdev.cweb.beans.prod.impl.ClientBean;
import com.kgdev.cweb.entities.prod.managed.Client;

@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {

	@EJB
	ClientBean clientBean;
	
	private static final long serialVersionUID = 1L;
	

	public String getClientName() {
		Principal user = getPrincipalUser();
		if (user == null)
			return "Guest";
		return clientBean.find(user.getName()).getName();
	}

	private Principal getPrincipalUser() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getUserPrincipal();
	}

	public boolean isAuthenticated() {
		return getPrincipalUser() != null;
	}

	public String logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		session.invalidate();
		return "toStoreHome";
	}

	public String getCurrentPage() {
		FacesContext fc = FacesContext.getCurrentInstance();
		return fc.getViewRoot().getViewId();
	}
	
	public Client getAutenticatedClient() {
		Principal user = getPrincipalUser();
		if (user == null)
			return null;
		return clientBean.find(user.getName());
	}
	
	public String getClientEmail() {
		return getPrincipalUser().getName();
	}
}
